package com.oocl.crm.parser.impl;

import com.oocl.crm.db.MyLinkedListFactory;
import com.oocl.crm.parser.CmdParser;
import com.oocl.crm.pojo.Customer;
import com.oocl.crm.repository.CustomerDataProcess;
import com.oocl.crm.repository.impl.CustomerDataProcessImpl;

public class CmdParserImpl implements CmdParser{
	private CustomerDataProcess cdp = new CustomerDataProcessImpl(MyLinkedListFactory.getInstance());
	private Customer customer;
	String[] fixArray ;
	public void processAdd(String cmd) {
		cdp.addCustomer(stringToCustomer(cmd));
	}

	public void processUpdate(String cmd) {
		cdp.updateCustomer(cmd.substring(2));
	}

	public void processDelete(String cmd) {
		cdp.deleteCustomer(Integer.parseInt(cmd.substring(2)));
	}

	public Customer[] processSort(String field) {
		return cdp.sort(field);
	}

	public Customer[] find(String cmd) {
		Customer[] find = cdp.find(parseString(cmd));
		return find;
	}
	
	private Customer stringToCustomer(String cmd){
		customer = new Customer();
		String realCmd = cmd.substring(2);
		String[] params = realCmd.split(",");
		String[] key = new String[6];
		String[] value = new String[6];
		for(int i = 0; i<params.length;i++){
			key[i] = params[i].substring(0,params[i].indexOf(":"));
			value[i] = params[i].substring(params[i].indexOf(":")+1);
		}
		for(int i = 0;i<key.length;i++){
			if("name".equals(key[i])){
				customer.setName(value[i]);
			}else if("sex".equals(key[i])){
				customer.setName(value[i]);
			}
			else if("birthday".equals(key[i])){
				customer.setName(value[i]);
			}
			else if("address".equals(key[i])){
				customer.setName(value[i]);
			}
			else if("call".equals(key[i])){
				customer.setName(value[i]);
			}
		}
		return customer;
		
	}

	private String[] parseString(String cmd){
		fixArray = new String[2];
		int flagFirst = cmd.indexOf(":");
		int flagLast = cmd.lastIndexOf(":");
		if(flagFirst == -1){
			fixArray[0] = "0";
		}else if(flagFirst ==flagLast && flagLast>1){
			fixArray[0] = "1";
		}else if(flagLast > flagFirst){
			fixArray[0] = "2";
		}
		fixArray[1] = cmd;
		return fixArray;
	}


}
